package com.gdcp.controller.backend;

import com.gdcp.beans.Banner;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.BannerService;
import com.gdcp.util.ImageDto;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.gdcp.util.ImageUtil.generateThumbnail;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/bannerManager")
@RolesAllowed({"ROLE_ADMIN"})
public class BannerController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    BannerService bannerService;

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber){
        Map<String, Object> param=new HashMap<>();
        int a=(pageNumber-1)*pageSize;
        int b=pageSize;
        param.put("a", a);
        param.put("b", b);
        return bannerService.findPageBreakByCondition(param);
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }
        return bannerService.removeByPrimaryKey(ids);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        return insertImage("insert",request,multipartResolver);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        return insertImage("edit",request,multipartResolver);
    }

    private Map<String,Object> insertImage(String str,HttpServletRequest request,CommonsMultipartResolver multipartResolver) {
        boolean str_boolean=str.equals("edit");
        // 若请求中存在文件流，则取出相关的文件
        try{
            if(multipartResolver.isMultipart(request)){
                //获取文件流中图片信息
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

                // 取出缩略图并构建ImageHolder对象
                Integer id=null;
                if (str_boolean) {
                    id = Integer.valueOf(multipartRequest.getParameter("id"));
                }

                String title = multipartRequest.getParameter("title");
                String url = multipartRequest.getParameter("url");
                Integer status = Integer.valueOf(multipartRequest.getParameter("status"));
                MultipartFile imageFile = multipartRequest.getFile("image");

                ImageDto mainImage=null;
                if (imageFile != null) {
                    mainImage = new ImageDto(imageFile.getOriginalFilename(), imageFile.getInputStream());
                }

                if (str_boolean){
                    Banner banner=new Banner();
                    banner.setId(id);
                    banner.setTitle(title);
                    banner.setUrl(url);
                    banner.setStatus(status);
                    return bannerService.updateInformation(banner,mainImage);
                }else {
                    Banner banner=new Banner();
                    banner.setUrl(url);
                    banner.setTitle(title);
                    banner.setStatus(status);
                    return bannerService.insert(banner,mainImage);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return responseModel.setModel(false,"操作失败");
        }
        return responseModel.setModel(false,"操作失败");
    }

    @PostMapping("/get/{id}")
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        Banner banner= bannerService.getInformation(id);
        if (banner!=null){
            return responseModel.setModel(true,banner);
        }

        return responseModel.setModel(false,"获取失败");
    }

    @PostMapping("/search")
    @ResponseBody
    public Map<String,Object> search(String searchText){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> param=new HashMap<>();

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            param.put("id", jsonOne.getString("id"));
            param.put("url", jsonOne.getString("url"));
            param.put("title", jsonOne.getString("title"));
        }
        return bannerService.searchInformation(param);
    }

    @PostMapping("/getImage")
    @ResponseBody
    public Map<String,Object> getImage(String urls){
        //String imgBase64 = request.getParameter("urls");
        if (urls==null||urls.equals("")){
            return responseModel.setModel(false,"返回路径为空");
        }

        String url=generateThumbnail(urls);
        if (url.equals("")){
            return responseModel.setModel(false,"返回路径为空");
        }

        return responseModel.setModel(true,url);
    }
}